<?php

class DrinkController extends ControllerBase
{
	public function init() {
            parent::init();
            $this->defaultAction = 'admin';
        }

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Drink;
		$lastID = Util::generalTableID(Drink::model(), 'drinkid');

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Drink']))
		{
			$model->attributes=$_POST['Drink'];			
                        $model->drinkprice = preg_replace('/\\s/', '', $_POST['Drink']['drinkprice']);
                        													
                        if ($lastID)
                            $model->drinkid = ++$lastID;
                        else
                            $model->drinkid = 0;
                        
                        $upload = CUploadedFile::getInstance($model, 'imgpath');
                        if ($upload != null)
                            $model->imgpath = $upload->name . "." . $upload->extensionName;
                        else
                            $model->imgpath = 'default';
							
			if($model->save()){
                            if ($upload != null) {
                                //$upload->saveAs(dirname(Yii::getPathOfAlias('webroot')) . "/" . SITE_FOLDER . "/uploads/images/menudrink/" . $upload->name . "." . $upload->extensionName);
								$upload->saveAs(Yii::getPathOfAlias('webroot') . "/uploads/images/menudrink/" . $upload->name);
                            }
                            
                            //add auto recipie for new drink
                            $recipie = new Recipie;
                            $lastID = Util::generalTableID(Recipie::model(), 'recipieid');
                            if ($lastID)
                                $recipie->recipieid = ++$lastID;
                            else
                                $recipie->recipieid = 0;
                            
                            $recipie->drinkid = $model->drinkid;
                            $recipie->active = 1;
                            $recipie->save();
                                                        
                            $this->setMessage('Create Drink Successful');
                            $this->refresh();
                        }
				
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}
        
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
                $oldImage = $model->imgpath;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Drink']))
		{
			$model->attributes=$_POST['Drink'];
                        $model->drinkprice = preg_replace('/\\s/', '', $_POST['Drink']['drinkprice']);
                        
                        $upload = CUploadedFile::getInstance($model, 'imgpath');
                        
                        if ($upload != null){
                            //$upload->saveAs(dirname(Yii::getPathOfAlias('webroot')) . "/" . SITE_FOLDER . "/uploads/images/menudrink/" . $upload->name . "." . $upload->extensionName);
							if (is_dir(Yii::getPathOfAlias('webroot') . "/uploads/images/menudrink/")){
								$upload->saveAs(Yii::getPathOfAlias('webroot') . "/" . SITE_FOLDER . "/uploads/images/menudrink/" . $upload->name );
								$model->imgpath = $upload->name;
							}								
                        }else
                            $model->imgpath = $oldImage;                            
                        
			if($model->save()){
                            $this->setMessage('Update Drink Successful');
                            $this->refresh();
                        }
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
//			$this->loadModel($id)->delete();
                        $recipie = Recipie::model()->find(array(
                            'condition' => 'drinkid = :id',
                            'params' => array(
                                ':id' => $id
                            )
                        ));
                        $recipie->active = 0;
                        $recipie->update('active');

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Drink('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Drink']))
			$model->attributes=$_GET['Drink'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Drink::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='drink-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        public function actionGetMenuList(){
            $menuDrink = array();
            $menuSyrup = array();
            $menuDrinkType = array();
            $menuDrink = array();
			$menu = array();
            
            $drinktypes = Drinktype::model()->findAll();			
            foreach ($drinktypes as $drinktype => $drinktypevalue){
//                $menuDrinkType[$drinktypevalue->drinktypeid] = $drinktypevalue->drinktypename;
                
                $drinks = Drink::model()->findAll(array(
                    'condition' => 'drinktypeid = :drinktypeid',
                    'params' => array(
                        ':drinktypeid' => $drinktypevalue->drinktypeid,
                    ),
                    'order' => 'drinkid',
                ));
                				
                foreach ($drinks as $drink => $drinkvalue){
                    $menu['menulist'][] = array(
                        'drinktypeid' => $drinkvalue->drinktypeid,
                        'drinkid' => $drinkvalue->drinkid,
                        'drinkname' => $drinkvalue->drinkname,
                        'price' => $drinkvalue->drinkprice,
                        'image' => is_null($drinkvalue->imgpath) ? "null" : $drinkvalue->imgpath,
                    );
                }				
            }    
			echo CJSON::encode($menu);
			exit(0);
        }
        
        public function actionGetVersionMenu(){
            $config = Config::model()->find(array(
                'condition' => 'name = "Menu Version"',
            ));
            echo CJSON::encode(array('verson' => $config->value));			
        }
        
        public function beforeAction($action) {
            parent::beforeAction($action);
            if (Yii::app()->user->id === null)
                $this->redirect(Yii::app()->createUrl('site/login'));
            return true;
        }
}